﻿import cv2
import numpy as np


# cv2.namedWindow("origin", 0)
# cv2.moveWindow("origin", 600, 100)
# cv2.resizeWindow("origin", 160, 210)
#
# cv2.namedWindow("bin", 0)
# cv2.moveWindow("bin", 800, 100)
# cv2.resizeWindow("bin", 160, 210)
#
# cv2.namedWindow("resized_screen", 0)
# cv2.moveWindow("resized_screen", 1000, 100)
# cv2.resizeWindow("resized_screen", 84, 110)
#
# cv2.namedWindow("x_t", 0)
# cv2.moveWindow("x_t", 1200, 100)
# cv2.resizeWindow("x_t", 84, 84)


def preprocess(observation):
    # img = np.reshape(observation, [210, 160, 3]).astype(np.float32)
    # RGB转换成灰度图像的一个常用公式是：ray = R*0.299 + G*0.587 + B*0.114
    # img = img[:, :, 0] * 0.299 + img[:, :, 1] * 0.587 + img[:, :, 2] * 0.114  # shape (210,160)
    observation = cv2.cvtColor(observation, cv2.COLOR_BGR2GRAY)
    ret, img = cv2.threshold(observation, 100, 255, cv2.THRESH_BINARY)

    resized_screen = cv2.resize(img, (84, 110), interpolation=cv2.INTER_AREA)  # shape(110,84)
    x_t = resized_screen[18:102, :]
    x_t = np.reshape(x_t, [84, 84, 1])
    x_t.astype(np.uint8)

    # cv2.imshow("origin", observation)
    # cv2.imshow("bin", img)
    # cv2.imshow("resized_screen", resized_screen)
    # cv2.imshow("x_t", x_t)

    x_t = np.moveaxis(x_t, 2, 0)  # shape（1，84，84）
    return np.array(x_t).astype(np.float32) / 255.0
